package com.wyq.miaosha.rabbitmq;

import com.wyq.miaosha.domain.MiaoshaOrder;
import com.wyq.miaosha.domain.MiaoshaUser;
import com.wyq.miaosha.domain.OrderInfo;
import com.wyq.miaosha.redis.RedisService;
import com.wyq.miaosha.result.CodeMsg;
import com.wyq.miaosha.result.Result;
import com.wyq.miaosha.service.GoodsService;
import com.wyq.miaosha.service.MiaoshaService;
import com.wyq.miaosha.service.OrderService;
import com.wyq.miaosha.vo.GoodsVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MQReceiver {

    private static Logger log = LoggerFactory.getLogger(MQReceiver.class);

    @Autowired
    AmqpTemplate amqpTemplate;
    @Autowired
    RedisService redisService;
    @Autowired
    GoodsService goodsService;
    @Autowired
    OrderService orderService;
    @Autowired
    MiaoshaService miaoshaService;

    @RabbitListener(queues = MQConfig.MIAOSHA_QUEUE)
    public void receiveMiaosha(String message){
        log.info("receive message: "+message);
        MiaoshaMessage mm = redisService.stringToBean(message,MiaoshaMessage.class);
        MiaoshaUser miaoshaUser = mm.getMiaoshaUser();
        long goodsId = mm.getGoodsId();

        //判断是否还有库存
        GoodsVo goodsVo = goodsService.getGoodsVoByGoodsId(goodsId);
        if(goodsVo.getStockCount() <= 0){
            return;
        }
        //判断是否已经秒杀到了
        MiaoshaOrder order = orderService.getMiaoshaOrderByUserIdGoodsId(miaoshaUser.getId(), goodsId);
        if(order != null) {
            return;
        }
        //减库存下订单
        OrderInfo miaosha = miaoshaService.miaosha(miaoshaUser, goodsVo);
    }

//    @RabbitListener(queues = MQConfig.QUEUE)
//    public void receive(String message){
//        log.info("receive message:"+message);
//    }
//
//    @RabbitListener(queues = MQConfig.TOPIC_QUEUE1)
//    public void receiveTopic1(String message){
//        log.info("receive message 1:"+message);
//    }
//
//    @RabbitListener(queues = MQConfig.TOPIC_QUEUE2)
//    public void receiveTopic2(String message){
//        log.info("receive message #:"+message);
//    }
//
//    @RabbitListener(queues = MQConfig.HEADERS_QUEUE)
//    public void receiveTopic2(byte[] message){
//        log.info("header message :" + new String(message));
//    }
}
